﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;

namespace PeisongWeb
{
    public partial class PricePublishDataService : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }

        private void parentCategoryBind()
        {
            DataTable dt = logic.category.getByParent(0);
            DataTable listPrice = logic.price.listWithAllParentCategory();

            // 创建目录
            CreateDateFolder();

            foreach (DataRow item in dt.Rows)
            {
                DataView dv = new DataView(listPrice);
                dv.RowFilter = string.Format("categoryId={0}", item["categoryId"]);

                StringBuilder contentBuffer = new StringBuilder();

                foreach (DataRowView row in dv)
                {
                    contentBuffer.AppendFormat("农副产品\t{0}\t{1}\t{2:F2}\t{3}\t{4}\r\n", item["name"], row["productName"], row["price"], row["unit"],DateTime.Now.ToString("yyyy-MM-dd"));
                }
                // 生成TXT文件
                CreateFile(item["name"].ToString(), contentBuffer.ToString());
            }

            // 创建zip文件

            string folderName = DateTime.Now.ToString("yyyyMMdd");
            string dirName = Server.MapPath("~/DataRespository/" + folderName);
            string zipFullPath = Server.MapPath("~/DataRespository/" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip");
            string zipFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".zip";

            using (MemoryStream ms = new MemoryStream())
            {
                FastZip fastZip = new FastZip();
                fastZip.CreateEmptyDirectories = true;
                fastZip.CreateZip(ms, dirName, true, "", "");
                fastZip = null;

                // Web下载
                HttpContext curContext = HttpContext.Current;
                curContext.Response.ContentType = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding = Encoding.UTF8;
                curContext.Response.Charset = "";
                curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(zipFileName, Encoding.UTF8));

                curContext.Response.BinaryWrite(ms.GetBuffer());
                curContext.Response.End();
            }
        }

        private void CreateDateFolder()
        {
            string folderName = DateTime.Now.ToString("yyyyMMdd");

            string dirName = Server.MapPath("~/DataRespository/" + folderName);

            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }
        }

        private void CreateFile(string fileName, string content)
        {
            string folderName = DateTime.Now.ToString("yyyyMMdd");
            string fullPath = Server.MapPath("~/DataRespository/" + folderName + "/" + fileName + ".txt");

            using (StreamWriter sw = new StreamWriter(fullPath, false, System.Text.Encoding.UTF8))
            {
                sw.Write(content);
                sw.Close();
            }
        }

        // 验证验证码是否正确
        private bool ValidateCode()
        {
            if (Request.Browser.Cookies)
            {
                if (String.Compare(Request.Cookies["CheckCode"].Value, txtValidateCode.Value, true) != 0)
                {

                    Library.Script.ClientMsg("你输入的验证码不正确，请重试.");
                    return false;
                }
                return true;
            }
            else
            {
                Library.Script.ClientMsg("你的浏览器阻止了cookie,网站需要开启cookie功能.");
                return false;
            }
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            bool isValidated = ValidateCode();

            if (isValidated)
            {
                parentCategoryBind();
            }
        }
    }
}
